package com.jusfoun.communication.service;

import com.jusfoun.communication.dao.UserDao;
import com.jusfoun.communication.model.User;
import com.jusfoun.communication.util.PageInfo;
import com.jusfoun.communication.util.Result;
import com.jusfoun.communication.util.ResultUtil;
import com.jusfoun.communication.websocket.WebSocketEndPoint;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 用户相关的操作service
 *
 * @author player six
 * @email jslcylcy@163.com
 * @create 2017-10-12 15:58
 **/
@Service
public class UserService {

    @Autowired
    private ResultUtil resultUtil;

    @Autowired
    private WebSocketEndPoint webSocketEndPoint;

    @Autowired
    private UserDao userDao;

    /**
     * websocket连接鉴权
     *
     * @param token
     * @return
     */
    public User checkWebSocketConn(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return userDao.getUserByToken(token);
    }

    /**
     * 将各个系统的用户记录下来
     *
     * @param user
     */
    public void addUser2List(User user) {
        userDao.addUserNotExist(user.getAppId(), user.getUserName());
    }

    /**
     * 给指定用户设置分组
     *
     * @param user
     * @return
     */
    public Result userGroup(User user) {
        //记录用户
        addUser2List(user);
        if (StringUtils.isNotBlank(user.getGroup())) {
            userDao.addGroupNotExist(user.getAppId(), user.getGroup());
        }
        userDao.updateUserGroup(user.getAppId(), user.getUserName(), user.getGroup());
        return resultUtil.success();
    }

    public Result userTags(User user) {
        //记录用户
        addUser2List(user);
        String[] tags = null;
        if (StringUtils.isNotBlank(user.getTags())) {
            tags = getValidTags(user.getTags());
            if (null == tags || tags.length == 0) {
                return resultUtil.fail("失败", "tags不合法");
            }
            for (String tag : tags) {
                userDao.addTagNotExist(user.getAppId(), tag);
            }
        }
        userDao.updateUserTags(user.getAppId(), user.getUserName(), tags);
        return resultUtil.success();
    }

    /**
     * 获取tags分组
     *
     * @param tags
     * @return
     */
    public String[] getValidTags(String tags) {
        String[] tagArray = tags.split(",");
        List<String> result = new ArrayList<>();
        for (String tag : tagArray) {
            if (StringUtils.isNotBlank(tag)) {
                result.add(tag.trim());
            }
        }
        return result.isEmpty() ? new String[]{} : result.toArray(new String[result.size()]);
    }

    /**
     * 获取指定tag下的用户列表
     *
     * @param tag
     * @param appId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<String> getTagUsers(String tag, String appId, Integer pageNum, Integer pageSize) {
        long total = userDao.listTagUserCount(appId, tag);
        if (total > 0) {
            PageInfo<String> userPageInfo = new PageInfo<>(pageNum, pageSize, total);
            userPageInfo.setList(userDao.listTagUser(appId, tag, userPageInfo));
            userPageInfo.calSize();
            return userPageInfo;
        }
        return new PageInfo<>();
    }


    /**
     * 获取指定appId下的用户列表
     *
     * @param appId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<User> listUsers(String appId, Integer pageNum, Integer pageSize) {
        long total = userDao.listUserCount(appId);
        if (total > 0) {
            PageInfo<User> userPageInfo = new PageInfo<>(pageNum, pageSize, total);
            userPageInfo.setList(userDao.listUser(appId, userPageInfo));
            userPageInfo.calSize();
            return userPageInfo;
        }
        return new PageInfo<>();
    }

    /**
     * 获取指定group下用户的分页信息
     *
     * @param user
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<String> getGroupUsers(User user, Integer pageNum, Integer pageSize) {
        long total = userDao.listGroupUserCount(user.getAppId(), user.getGroup());
        if (total > 0) {
            if (StringUtils.isBlank(user.getStatus())) {
                PageInfo<String> userPageInfo = new PageInfo<>(pageNum, pageSize, total);
                userPageInfo.setList(userDao.listGroupUser(user.getAppId(), user.getGroup(), userPageInfo));
                userPageInfo.calSize();
                return userPageInfo;
            } else {
                //只取在线或者离线用户
                return getGroupUsersByStatus(user, pageNum, pageSize, total);
            }

        }
        return new PageInfo<>();
    }

    private PageInfo<String> getGroupUsersByStatus(User user, Integer pageNum, Integer pageSize, long total) {
        PageInfo<String> userPageInfo = new PageInfo<>(0, 0, total);
        List<String> userList = userDao.listGroupUser(user.getAppId(), user.getGroup(), userPageInfo);
        Iterator<String> iterator = userList.iterator();
        while (iterator.hasNext()) {
            String userName = iterator.next();
            User u = new User();
            u.setAppId(user.getAppId());
            u.setUserName(userName);
            webSocketEndPoint.checkUserStatus(u);
            if (!user.getStatus().equals(u.getStatus())) {
                iterator.remove();
            }
        }
        userPageInfo = new PageInfo<>(pageNum, pageSize, Long.valueOf(userList.size()));
        if (userPageInfo.getStartRow() > 0 && userPageInfo.getEndRow() > userPageInfo.getStartRow()) {
            userPageInfo.setList(userList.subList(userPageInfo.getStartRow() - 1, userPageInfo.getEndRow()));
        } else {
            userPageInfo.setList(userList);
        }
        userPageInfo.calSize();
        return userPageInfo;
    }

    /**
     * 获取所有分组,可分页
     *
     * @param appId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<String> getGroups(String appId, Integer pageNum, Integer pageSize) {
        long total = userDao.listGroupCount(appId);
        if (total > 0) {
            PageInfo<String> groupPageInfo = new PageInfo<>(pageNum, pageSize, total);
            groupPageInfo.setList(userDao.listGroup(appId, groupPageInfo));
            groupPageInfo.calSize();
            return groupPageInfo;
        }
        return new PageInfo<>();
    }

    /**
     * 获取所有标签
     *
     * @param appId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<String> getTags(String appId, Integer pageNum, Integer pageSize) {
        long total = userDao.listTagCount(appId);
        if (total > 0) {
            PageInfo<String> groupPageInfo = new PageInfo<>(pageNum, pageSize, total);
            groupPageInfo.setList(userDao.listTag(appId, groupPageInfo));
            groupPageInfo.calSize();
            return groupPageInfo;
        }
        return new PageInfo<>();
    }

    /**
     * 获取用户状态(在线,离线)
     *
     * @param appId
     * @param userName
     * @return
     */
    public Result checkUserStatus(String appId, String userName) {
        User u = new User();
        u.setAppId(appId);
        u.setUserName(userName);
        webSocketEndPoint.checkUserStatus(u);
        return resultUtil.success("成功", "查询当前用户状态成功", u);
    }

    /**
     * 返回appId下所有的用户列表
     *
     * @param appId
     * @return
     */
    public List<String> listAllByAppId(String appId) {
        return userDao.listAllUserName(appId);
    }

    /**
     * 生成用户token
     *
     * @param user
     * @return
     */
    public String generateToken(User user) {
        return userDao.generateToken(user.getAppId(), user.getUserName());
    }
}
